from mtp.lib.base import *
from mtp.model import *
from mtp.lib.plugin import Plugin 
from mtp.lib.pageaction import PageAction


WikiStructureTable = Table('wiki_structure', plugin_meta,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('page_id', Integer, ForeignKey(PagesTable.c.id)),
    Column('parent_id', Integer, ForeignKey(PagesTable.c.id)),
)

class WikiStructure(ObjBase):
    @classmethod
    def children(klass, page):
        return (Session.query(klass)
                .filter(klass.parent_id==page.id)
                .all()
        )

    @classmethod
    def parents(klass, page):
        return (Session.query(klass)
                .filter(klass.page_id==page.id)
                .all()
        )

    @classmethod
    def parent(klass, page, parent_page):
        ws = WikiStructure(page_id=page.id, parent_id=parent_page.id)
        ws.save()
        return ws

mapper(WikiStructure, WikiStructureTable, properties={
    'page': relation(Page, primaryjoin=(PagesTable.c.id==WikiStructureTable.c.page_id)),
    'parent_page': relation(Page, primaryjoin=(PagesTable.c.id==WikiStructureTable.c.parent_id)),
})


class WikiStructurePlugin(Plugin):
    tables = [WikiStructureTable]

    def __init__(self, **options):
        config['mtp.content.append'][('pages', 'show')].append(self.pageContent)
        #config['mtp.page_actions'][('pages', 'show')].append(self.pageActions)
        config['mtp.extra_css'].append('/wikistructure/wikistructure.css')
        config['mtp.edit_page.content.insert'].append(self.editInsert)
        config['mtp.edit_page.processors'].append(self.editProcess)
        
    def pageContent(self):
        c.children = WikiStructure.children(c.page)
        c.parents = WikiStructure.parents(c.page)
        if c.children or c.parents:
            return mako_render('/wikistructure/list_frag.html')

    #def pageActions(self):
    #    return (
    #        PageAction('Create Child Page', h.url_for('new_page', parent=c.page.id)),
    #    )

    def editInsert(self):
        if c.last_page:
            return ('', mako_render('/wikistructure/edit_frag.html'))

    def editProcess(self):
        if request.params.has_key('wikistructure_child'):
            parent_id = request.params.get('wikistructure_parent_id')
            parent_page = model.Page.get(parent_id)
            #StructureTag.add(c.page.id, 'parent:%s' % parent_page.id)        
            WikiStructure.parent(c.page, parent_page)
            
            
                



